import{ref,type Ref,onMounted} from 'vue'
import { RequestCategory,RequestGoodsByCategoryId } from '@/api/category'
import type{ IGoods,ICategory } from '@/types/types'
//商品分类
export const useCategory=()=>{
    const activeId:Ref<number> = ref(1)
    const activeIndex:Ref<number>  = ref(0)
    const categoryList:Ref<Array<ICategory>>=ref([])
    const categoryGoodsList:Ref<Array<IGoods>>=ref([])
    const categoryGoods:Ref<Array<IGoods>>=ref([])
  
    const getCategory=async ()=>{
        const data = await RequestCategory()
        const {resultCode,resultInfo} = data
        if(resultCode===1){
            
         categoryList.value = resultInfo.list.map((item:ICategory)=>{
               return {id:item.id,name:item.name,text:item.name}
         })
         const categoryId = categoryList.value[0].id
         getGoodsByCategoryId(categoryId)
        }
        
    }
    const getGoodsByCategoryId = async (categoryId: number) => {
        const data = await RequestGoodsByCategoryId(categoryId)
        const { resultCode, resultInfo } = data
        
        if (resultCode === 1) {
           
            categoryGoods.value = resultInfo.list
            
    }}
    const bindClickChange = (index:number) => {
        const categoryId = categoryList.value[index].id
        getGoodsByCategoryId(categoryId)
        
    }
    const filterUrl=(url:string)=> {
        return url?.indexOf('http') === -1
            ? 'http://124.71.63.13:8088/' + url
            : url
    }
onMounted(()=>{
    getCategory()
   
})
    

return { activeIndex,categoryList,categoryGoods,bindClickChange,filterUrl }}
